from json.decoder import JSONDecodeError
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.conf import settings
from .models import Music
from .util.pick_music_from_bilibili import pick_music_from_bilibili

def allmusic(request):
    all_music = Music.objects.all()
    data = []
    for e in all_music:
        data.append({
            "music_id": e.music_id,
            "music_name": e.music_name,
            "music_up": e.music_up,
            "music_bv": e.music_bv,
            "music_release_time": e.music_release_time,
            "music_file_path": settings.MUSIC_FILE_URL + e.music_file_path,
            "music_image_path": settings.MUSIC_IMAGE_URL + e.music_image_path
        })
    return JsonResponse({"status": "success", "data": data, "explain": "success"})


def music(request):
    query_params = request.GET
    if 'id' not in query_params.keys():
        return JsonResponse({"status": "warning", "data": "", "explain": "without query param 'id'"})
    query_id = query_params['id']
    e = Music.objects.filter(music_id=query_id)
    if len(e) == 0:
        return JsonResponse({"status": "warning", "data": "", "explain": "no music in such id"})
    e = e[0]
    data = {
        "music_id": e.music_id,
        "music_name": e.music_name,
        "music_up": e.music_up,
        "music_bv": e.music_bv,
        "music_release_time": e.music_release_time,
        "music_file_path": settings.MUSIC_FILE_URL + e.music_file_path,
        "music_image_path": settings.MUSIC_IMAGE_URL + e.music_image_path
    }
    return JsonResponse({"status": "success", "data": data, "explain": "success"})


def pickmusic(request):
    query_params = request.GET
    if 'bv' not in query_params.keys():
        return JsonResponse({"status": "warning", "data": "", "explain": "without query param 'bv'"})
    query_bv = query_params['bv']

    try:
        music_name, music_up, music_bv, music_release_time, music_file_path, music_image_path = pick_music_from_bilibili(query_bv)
        music = Music(music_name=music_name, music_up=music_up, music_bv=music_bv, 
                    music_release_time=music_release_time, music_file_path=music_file_path, 
                    music_image_path=music_image_path)
        music.save()
        return JsonResponse({"status": "success", "data": "", "explain": "success"})
    except Exception as e:
        print()
        print(e)
        print()
        return JsonResponse({"status": "warning", "data": "", "explain": "some error occur!"})